package com.rt.tmpt.others.singleuser;

import com.rt.tmpt.utils.DateTool;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import java.util.ArrayList;
import java.util.List;

public class OnlineUserBindingListener implements HttpSessionBindingListener {
	private Userinfo userinfo = new Userinfo();
	
	public OnlineUserBindingListener(String username) {
		this.userinfo.setUsername(username);
		this.userinfo.setLastAccessTime(DateTool.getCurrentDatetime());
	}
	
	@Override
	public void valueBound(HttpSessionBindingEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		List<Userinfo> onlineUserList = (List<Userinfo>)application.getAttribute("onlineUserList");
		//第一次使用要初始化一下
		if(onlineUserList==null){
			onlineUserList = new ArrayList<Userinfo>();
			application.setAttribute("onlineUserList", onlineUserList);
		}
		onlineUserList.add(this.userinfo);
		System.out.println(this.userinfo.getUsername() + "登录");
	}
	
	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		application.removeAttribute("onlineUserList");
		System.out.println(this.userinfo.getUsername() + "退出");
	}
}
